package com.yin.rwlock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
ReadWriteLock
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();

        // Write loop
        for (int i = 1; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }

        // Read loop
        for (int i = 1; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, String.valueOf(i)).start();
        }
    }
}

/*
自定义缓存
 */
class MyCache {
    private final Map<String, Object> map = new HashMap<>();

    // 存，write
    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "Write" + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "Write" + key + "Done");
    }

    // 取，read
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "Read" + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "Read" + key + "Done");
    }

}/*
自定义缓存,加锁的
 */
class MyCacheLock {
    private final Map<String, Object> map = new HashMap<>();
    // 读写锁 更加细粒度的控制
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    // 存，write，只希望同时只有一个线程写
    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "Write" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "Write" + key + "Done");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    // 取，read，所有线程都可以读
    public void get(String key) {
        readWriteLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName() + "Read" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "Read" + key + "Done");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }

}
